﻿using PeiYue.IRepository.Base;
using PeiYue.IServices.Store;
using PeiYue.Model.Dto.Purchase;
using PeiYue.Model.Models.Store;
using PeiYue.Services.BASE;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;

namespace PeiYue.Services.Store
{
    public class ReceiptRecordServices : BaseServices<ReceiptRecord>, IReceiptRecordServices
    {
        IBaseRepository<ReceiptRecord> _dal;
        public ReceiptRecordServices(IBaseRepository<ReceiptRecord> dal)
        {
            this._dal = dal;
            base.BaseDal = dal;
        }

        public async Task<bool> SetReceiptRecords(List<ReceiptRecord> models)
        {

            var bars = models.Select(i => i.BarCode).ToArray();

            await _dal.Update("update oms_srm_receipt_record set Status=0 where BarCode in (@BarCode)", new { BarCode = bars });

            bool res = false;
            res = await _dal.Add(models) > 0;
            foreach (var iteam in models)
            {
                if (iteam.ReceiptQty == 0)
                {
                    string upSQL = @"update [供应链].[dbo].采购订单表体  set [缺货数]=(    select   sum(s.数量)    FROM  [供应链].[dbo].[v仓库拣选日志] S
  LEFT JOIN(select BarCode, receiptQty from [oms].[dbo].[oms_srm_receipt_record] where Status = 1) R ON   BarCode = 条码
  WHERE s.采购ID = @FID  and isnull(r.receiptQty,-999)= 0  ) ,收货数=(    select   sum(r.receiptQty)    FROM  [供应链].[dbo].[v仓库拣选日志] S
  LEFT JOIN(select BarCode, receiptQty from [oms].[dbo].[oms_srm_receipt_record] where Status = 1) R ON   BarCode = 条码
  WHERE s.采购ID = @FID  and isnull(r.receiptQty,-999)> 0  )  where fID=";
                    string sql = $@"{upSQL}@FID ;  exec [系统].[dbo].[p日志记录] 'OMS.Wechat',' ','','','{iteam.UserName}','供应商打码缺货,同步缺货数量','数据库','{upSQL + iteam.FID}','','{DateTime.Now}' ";
                    await _dal.ExecuteCommand(sql, new { iteam.FID });
                }

            }
            return res;

            ////ForEach
            //var Model = new List<ReceiptRecord>();
            //foreach (var iteam in models)
            //    if (iteam.Id > 0) Model.Add(iteam);// else newModel.Add(iteam);
            //var insertList = models.Where(i => i.Status == 1).ToList();
            //if (insertList.Count > 0)
            ////var oldModel = new List<ReceiptRecord>();
            //var oldModel = models.Where(i => i.Id > 0).ToList();
            //oldModel.ForEach(i => i.Status = 0);
            //if (oldModel.Count > 0) res = await _dal.Updates(oldModel);

        }
        public async Task UpdateReceiptRecordStatus(int fID)
        {
            await _dal.Update("update oms_srm_receipt_record set Status=0 where FID =@FID ", new { FID = fID });
        }
    }
}
